﻿using System;
using System.Collections.Generic;
using System.Text;
using AudioPlayer.Plugin.Tags;
using System.IO;
using System.Threading;

namespace AudioPlayer.Plugin {
	internal class DefaultWatcher : IWatcher {
		#region Variables
		private IList<String> _files;

		private string _root;
		private IList<string> _seekFor;
		#endregion
		#region Private Voids
		private void ScanDir(string root,IList<string> seekFor) {
			foreach (string dir in Directory.GetDirectories(root)) {
				this.ScanDir(dir, seekFor);
			}
			foreach (FileInfo file in new DirectoryInfo(root).GetFiles()) {
				foreach (string end in seekFor) {
					if (file.FullName.EndsWith(end)) {
						_files.Add(file.FullName);
					}
				}
			}
		}
		private void StartThread() {
			Thread worker = new Thread(new ThreadStart(Work));
			worker.Priority = ThreadPriority.Lowest;
			worker.Start();
		}

		private void Work() {
			//Scan files
			this.ScanDir(_root, _seekFor);
			//Notify listeners
			this.OnUpdate();
		}
		#endregion
		#region Public Voids

		/// <summary>
		/// Scans specified root folder, and seeks for files with extensions.
		/// Normaly will be runed as Thread.
		/// </summary>
		/// <param name="root">The root directory.</param>
		/// <param name="extensions">The extensions to seek.</param>
		public void Scan(string root, IList<string> extensions) {
			_files = new List<String>();
			_root = root;
			_seekFor = extensions;
			this.StartThread();
		}

		/// <summary>
		/// Gets new founded files.
		/// </summary>
		/// <returns></returns>
		public IList<string> GetFiles() {
			return new List<string>(((List<String>)_files).ToArray());
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		public void Dispose() {
			
		}

		protected void OnUpdate() {
			if (Update != null) {
				this.Update(this, EventArgs.Empty);
			}
		}
		#endregion
		#region Property
		protected IList<String> Files {
			get {
				return _files;
			}
			set { _files = value; }
		}
		#endregion
		#region Events
		/// <summary>
		/// Occurs when founds new files.
		/// </summary>
		public event EventHandler Update;
		#endregion
	}
}
